#include "dyn_roots_secantMethod.h"

SecantMethod::SecantMethod(Functor &func,
                           double init,
                           double init2,
                           const double tol,
                           const int Nmax)
    : function(func)
{
    setInitialValue(init);
    setInitialValue2(init2);
    setTolerance(tol);
    setMaxIterations(Nmax);
}

/*! We reimplement the pure virtual method.
 * We apply the standard secant method algorithm.
 * If the method succeeds, we return 0. A return
 * value of 1 means that the method failed to attain
 * our tolerance within the maximum number of iterations
 * constraint.
 */
int SecantMethod::solve()
{
    // We start the clock.
    start = clock();

    // We initialize the returnCode.
    // A priori, the method fails.
    int returnCode(1);

    // We set the root to the initial value.
    // We will update the value.
    double a = initialValue;
    double b = initialValue2;

    // Actual numerical computation.
    for (int i=0;i<maxIterations;i++)
    {
        // Correction term
        double dx = function(b)*(b-a)/(function(b)-function(a));

        if (fabs(dx) < tolerance)
        {
            root = b;
            returnCode = 0;
            break;
        }
        else
        {
            a=b;
            b -= dx;
            iterations++;
            continue;
        }
    }
    end = clock();
    processorTime = ((double) (end-start))/ CLOCKS_PER_SEC;
    return returnCode;
}
